package com.ruoyi.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class FileUtils {

    public static String getFileMD5(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath)) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length); // 更新哈希值
            }
            // 将 128 位哈希值转换为 32 位十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : md.digest()) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    // 工具方法：去除文件后缀
    public static String getFileNameWithoutExtension(File file) {
        String name = file.getName();
        int lastDotIndex = name.lastIndexOf(".");
        return lastDotIndex == -1 ? name : name.substring(0, lastDotIndex);
    }
}
